///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.data.format {
	import flash.events.EventDispatcher;
	
	import mx.utils.ObjectUtil;
	
	import sugarcookie.data.vo.AppData;
	import sugarcookie.data.vo.Common;
	import sugarcookie.data.vo.Component;
	import sugarcookie.data.vo.Group;
	import sugarcookie.data.vo.Meta;
	import sugarcookie.data.vo.View;
	
	public class XMLFormatter extends EventDispatcher {
		
		public static function parseXML(xml:XML):AppData {
			var data:AppData = new AppData();
			data.id = xml.@name;
			
			if (xml.metadata!=undefined) data.meta = parseMeta(xml.metadata[0]);
			if (xml.commondata!=undefined) data.common = parseCommon(xml.commondata[0]);
			
			for (var i:int=0;i<xml.view.length();i++) {
				var v:View = new View(xml.view[i].@id);
				var cmpt:XMLList = xml.view[i].component;
				for (var c:int=0;c<cmpt.length();c++) { //add components to view
					var tmpCmpt:Component = parseComponent(cmpt[c]);
					tmpCmpt.index = c;
					v[tmpCmpt.id] = tmpCmpt;
				}
				
				if (xml.view[i].group!=undefined) { //if there are groups
					var grp:XMLList = xml.view[i].group;
					for (var g:int=0;g<grp.length();g++) { //create group
						var tmpGrp:Group = parseGroup(grp[g]);
						tmpGrp.index = g;
						if (grp.metadata!=undefined) tmpGrp.meta = parseMeta(grp.metadata[0]);
						v[tmpGrp.id] = tmpGrp;
					}
				}
				
				data[v.id] = v;
			}
			
			return data;
		}
		
		private static function parseMeta(xml:XML):Meta {
			var data:Meta = new Meta();
			for (var c:int=0;c<xml.param.length();c++) data[xml.param[c].@id] = xml.param[c];
			return data;
		}
		
		private static function parseCommon(xml:XML):Common {
			var data:Common = new Common();
			return data;
		}
		
		private static function parseComponent(xml:XML):Component {
			var data:Component = new Component(xml.@id);
			for (var c:int=0;c<xml.param.length();c++) {
				data[xml.param[c].@id] = xml.param[c];
			}
			return data;
		}
		
		private static function parseGroup(xml:XML):Group {
			var data:Group = new Group(xml.@id,xml.@type);
			if (xml.component!=undefined) {
				var cmpt:XMLList = xml.component;
				for (var x:int=0;x<cmpt.length();x++) { //add components to group
					var tmp:Component = parseComponent(cmpt[x]);
					tmp.index = x;
					data[tmp.id] = tmp;
				}
			}
			
			if (xml.group!=undefined) { //if there are groups
				var grp:XMLList = xml.group;
				for (var n:int=0;n<grp.length();n++) { //create group
					var tmpGrp:Group = parseGroup(grp[n]);
					tmpGrp.index = n;
					data[tmpGrp.id] = tmpGrp;
				}
			}
			return data;
		}
	}
}